from django import template
from datetime import datetime
from django.utils.timezone import now as aware_now,localtime
from utils.datetime_paser import str_to_datetime


register = template.Library()


@register.filter
def time_since(value):
    if isinstance(value,str):
        try:
            value = str_to_datetime(value)
        except:
            return value
    elif isinstance(value,datetime):
        pass
    else:
        return value

    now = aware_now()
    timestamp = (now - value).total_seconds()
    if timestamp < 60:
        return '刚刚'
    elif 60 <= timestamp < 60 * 60:
        minutes = int(timestamp / 60)
        return '{}分钟前'.format(minutes)
    elif 60 * 60 <= timestamp < 60 * 60 * 24:
        hours = int(timestamp / 3600)
        return '{}小时前'.format(hours)
    elif 60 * 60 * 24 <= timestamp < 60 * 60 * 24 * 30:
        days = int(timestamp / 3600 / 24)
        return '{}天前'.format(days)
    else:
        return value.strftime('%Y-%m-%d')



